package com.example.desksginktapp.wigit

import android.content.Context
import android.os.Bundle
import android.text.InputType
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.view.inputmethod.InputMethodManager
import android.widget.Button
import android.widget.EditText
import android.widget.ImageButton
import android.widget.TextView
import androidx.fragment.app.DialogFragment
import com.example.baselibrary.bases.Constants
import com.example.baselibrary.bases.Constants.MEDATIONID
import com.example.baselibrary.utlis.AppCache
import com.example.baselibrary.utlis.AppInfoUtil
import com.example.desksginktapp.R
import java.lang.ref.WeakReference

class PasswordDialogFragment : DialogFragment() {

    private lateinit var passwordInput: EditText
    private lateinit var errorText: TextView
    private var listener: PasswordDialogListener? = null
    private var errorHideRunnable: Runnable? = null
    private var currentAnimation: Animation? = null
    private var isPasswordVisible = false
    private var  eyeState = "false"
    interface PasswordDialogListener {
        fun onPasswordCorrect()
        fun onDialogDismissed()
    }

    fun setPasswordDialogListener(listener: PasswordDialogListener) {
        this.listener = listener
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.dialog_password, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        eyeState = AppCache.get()?.getAsString(Constants.EYESTATE) ?: "false"
        // 设置对话框窗口属性
        dialog?.window?.setBackgroundDrawableResource(android.R.color.transparent)
        dialog?.setCanceledOnTouchOutside(false)

        // 初始化视图
        passwordInput = view.findViewById(R.id.passwordInput)
        errorText = view.findViewById(R.id.errorText)

        // 注意：检查布局中是否真的存在 toggleVisibility
        // 如果不存在，需要从布局中移除相关代码
        val toggleVisibility = view.findViewById<ImageButton>(R.id.toggleVisibility)
        val cancelButton = view.findViewById<Button>(R.id.cancelButton)
        val confirmButton = view.findViewById<Button>(R.id.confirmButton)

        // 根据 eyeState 初始化密码可见性状态
        initializePasswordVisibility()
        // 密码可见性切换（如果控件存在）
        toggleVisibility?.setOnClickListener {
            togglePasswordVisibility()
        }

        // 设置按钮点击事件
        cancelButton.setOnClickListener {
            dismissWithAnimation()
        }

        confirmButton.setOnClickListener {
            validatePassword()
        }
    }
    private fun initializePasswordVisibility() {
        // 根据 eyeState 设置初始状态
        isPasswordVisible = eyeState == "true"
        updatePasswordVisibilityState(isPasswordVisible)
        // 确保光标在文本末尾
        passwordInput.setSelection(passwordInput.text.length)
    }

    private fun updatePasswordVisibilityState(visible: Boolean) {
        if (visible) {
            // 显示密码（保持数字输入类型）
            passwordInput.inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_VARIATION_NORMAL
            view?.findViewById<ImageButton>(R.id.toggleVisibility)
                ?.setImageResource(R.drawable.ic_visibility)
        } else {
            // 隐藏密码（保持数字输入类型）
            passwordInput.inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_VARIATION_PASSWORD
            view?.findViewById<ImageButton>(R.id.toggleVisibility)
                ?.setImageResource(R.drawable.ic_visibility_off)
        }
    }

    override fun onStart() {
        super.onStart()
        // 设置对话框动画
        dialog?.window?.setWindowAnimations(R.style.DialogAnimation)
    }

    private fun togglePasswordVisibility() {
        isPasswordVisible = !isPasswordVisible

        // 保存当前光标位置
        val selectionStart = passwordInput.selectionStart
        val selectionEnd = passwordInput.selectionEnd

        if (isPasswordVisible) {
            // 显示密码
            passwordInput.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
            // 更新图标
            view?.findViewById<ImageButton>(R.id.toggleVisibility)
                ?.setImageResource(R.drawable.ic_visibility)
            AppCache.get()?.put(Constants.EYESTATE, "true")
        } else {
            // 隐藏密码
            passwordInput.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
            // 更新图标
            view?.findViewById<ImageButton>(R.id.toggleVisibility)
                ?.setImageResource(R.drawable.ic_visibility_off)
            AppCache.get()?.put(Constants.EYESTATE, "false")
        }

        // 恢复光标位置
        passwordInput.setSelection(
            selectionStart.coerceAtMost(passwordInput.text.length),
            selectionEnd.coerceAtMost(passwordInput.text.length)
        )
    }


    private fun validatePassword() {
        val password = passwordInput.text.toString().trim()

        when {
            password.isEmpty() -> {
                showError("密码不能为空")
            }
            password.length < 6 -> {
                showError("密码长度不能少于6位")
            }
            password == "123456" -> { // 示例密码，实际应用中应该使用安全验证
                listener?.onPasswordCorrect()
                dismissWithAnimation()
            }
            else -> {
                showError("密码不正确，请重试")
            }
        }
    }

    private fun showError(message: String) {
        // 检查 Fragment 是否仍然有效
        if (!isAdded || isDetached || context == null) {
            return
        }

        errorText.text = message
        errorText.visibility = View.VISIBLE
        errorText.alpha = 1.0f

        // 取消之前的隐藏任务
        errorHideRunnable?.let { errorText.removeCallbacks(it) }

        // 对整个对话框应用抖动动画
        val shake = AnimationUtils.loadAnimation(requireContext(), R.anim.shake)
        view?.startAnimation(shake)

        // 创建新的隐藏任务（使用淡出动画）
        errorHideRunnable = Runnable {
            // 再次检查 Fragment 状态
            if (!isAdded || isDetached || context == null) {
                return@Runnable
            }

            val fadeOut = AnimationUtils.loadAnimation(requireContext(), R.anim.fade_out)
            fadeOut.setAnimationListener(object : Animation.AnimationListener {
                override fun onAnimationStart(animation: Animation?) {}

                override fun onAnimationEnd(animation: Animation?) {
                    if (!isAdded || isDetached || context == null) {
                        return
                    }
                    errorText.visibility = View.INVISIBLE
                }

                override fun onAnimationRepeat(animation: Animation?) {}
            })
            errorText.startAnimation(fadeOut)
        }.also {
            // 3秒后隐藏错误提示
            errorText.postDelayed(it, 3000)
        }
    }




    private fun dismissWithAnimation() {
        // 取消当前动画
        currentAnimation?.setAnimationListener(null)

        // 应用退出动画
        val exitAnim = AnimationUtils.loadAnimation(requireContext(), R.anim.dialog_exit)
        currentAnimation = exitAnim
        view?.startAnimation(exitAnim)

        // 使用静态内部类避免内存泄漏
        exitAnim.setAnimationListener(DismissAnimationListener(this))
    }

    // 静态内部类避免持有外部类引用
    private class DismissAnimationListener(fragment: PasswordDialogFragment) : Animation.AnimationListener {
        private val fragmentRef = WeakReference(fragment)

        override fun onAnimationStart(animation: Animation?) {}

        override fun onAnimationEnd(animation: Animation?) {
            fragmentRef.get()?.apply {
                currentAnimation = null
                dismiss()
                listener?.onDialogDismissed()
            }
        }

        override fun onAnimationRepeat(animation: Animation?) {}
    }

    override fun onDestroyView() {
        // 清理资源
        cleanupResources()
        super.onDestroyView()
    }

    override fun onDestroy() {
        // 双重保险清理资源
        cleanupResources()
        super.onDestroy()
    }

    private fun cleanupResources() {
        // 取消错误提示隐藏任务
        errorHideRunnable?.let { errorText.removeCallbacks(it) }
        errorHideRunnable = null

        // 清理动画监听器
        currentAnimation?.setAnimationListener(null)
        currentAnimation = null

        // 清理监听器引用
        listener = null
    }
}
